<template>
	<view class="app">
		<!-- <view class="price-box">
			<text>订单号</text>
			<text>{{orderId}}</text>
			<text>支付金额</text>
			<text class="price">{{payAmount}}</text>
		</view> -->
		
		<view class="price-box">
			<text class="price num-font">{{payAmount}}</text>
			<!-- <text>订单号</text>
			<text>{{orderInfo.orderSn}}</text> -->
			<!-- <text>支付金额</text> -->
			<text>请在00:24:00内完成支付</text>
		</view>
		<!-- <view class="price-box">
			
		</view> -->

		<view class="pay-type-list">
			<view class="type-item b-b" @click="changePayType(1)">
				<text class="icon yticon icon-weixinzhifu"></text>
				<view class="con">
					<text class="tit">微信支付</text>
					<text>推荐使用微信支付</text>
				</view>
				<label class="radio">
					<radio value="" color="#FFBC21" :checked='payType == 1' />
				</label>
			</view>
			<!-- #ifdef APP-PLUS -->
			<view class="type-item b-b" @click="changePayType(2)">
				<text class="icon yticon icon-alipay"></text>
				<view class="con">
					<text class="tit">支付宝支付</text>
				</view>
				<label class="radio">
					<radio value="" color="#FFBC21" :checked='payType == 2' />
				</label>
			</view>
			<!-- #endif -->
			<!-- 现金支付功能暂时屏蔽 -->
			<!-- <view class="type-item" @click="changePayType(3)">
				<text class="icon yticon icon-erjiye-yucunkuan"></text>
				<view class="con">
					<text class="tit">预存款支付</text>
					<text>可用余额 ¥198.5</text>
				</view>
				<label class="radio">
					<radio value="" color="#FFBC21" :checked='payType == 3' />
					</radio>
				</label>
			</view> -->
		</view>
		<view class="footer">
			<button type="default" class="pay-botton" @click="confirmPay">确认支付</button>
		</view>
		<!-- <text class="mix-btn" ></text> -->
		<!-- <text class="mix-btn" @click="wxAuthorize">获取Code</text> -->
	</view>
</template>

<script>
	import Api from '@/common/api';
	import wexinPay from '@/common/wxPay.js'
	import CommonPay from '@/common/commonPay.js'
	import {
		mapMutations
	} from 'vuex';
	
	let commonPay = null;
	export default {
		data() {
			return {
				payType: 1,
				trade_type: '',
				orderId: '',
				payAmount: 0,
				url: '',
				type: 0, // type 1为购物车创建订单， 2立即下单  3,购买会员 4.代理商购买
				state: '',
			};
		},
		onLoad(options) {
			this.orderId = options.id;
			this.type = options.type;
			let userInfo = uni.getStorageSync('userInfo');
			// #ifdef H5
			this.trade_type = 'JSAPI';
			let isWeiXin = wexinPay.isWechat();
			if (isWeiXin && !userInfo.we_chat_openid) {
				//客户端为微信浏览H5
				this.wxAuthorize();
				return false;
			}
			// #endif
			// #ifdef MP-WEIXIN
			if (!userInfo.mini_openid) {
				//客户端为微信小程序
				this.minApp_Authorize();
				return false;
			}
			// #endif
			this.loadData();

		},
		onShow(options){
		},
		methods: {
			...mapMutations(['login']),
			//选择支付方式
			changePayType(type) {
				this.payType = type ? type : 0;
			},
			async loadData() {
				let params = {
						'id': this.orderId,
						type: 0 //0默认为主订单、1为子订单
					},
					data = await Api.apiCall('post', Api.order.orderDetail, params);
				if (data) {
					this.orderId = data.id;
					this.payAmount = data.pay_amount;
					if (data.order_type == 0) {
						this.url = '/pages/money/paySuccess?payType='
					} else {
						// type=0 表示是从支付完后跳转到确认收货地址页面 1.表示从领取vip_gif按钮进去，2.表示从agent_gif页面进去
						this.url = '/pages/money/memberPaySuccess?type=' + this.type + '&payType='
					}
				}
				commonPay = new CommonPay( this.orderId, this.payAmount, this.url);
			},
			// 用户点击支付方式处理
			confirmPay() {
				// #ifdef H5
				this.wechatH5pay();
				// #endif
				// #ifdef APP-PLUS
				switch (this.payType) {
					case 1:
						this.trade_type = 'APP'
						this.wechatPay()
						break
					case 2:
						this.trade_type = 'alipayApp'
						this.aliPay()
						break
				}
				// #endif
				// #ifdef MP-WEIXIN
				this.trade_type = 'MINIAPP'
				this.weixinAppletPay(); //微信小程序支付
				// #endif
			},
			// app 微信支付
			wechatPay() {
				commonPay.weChatPay(this.trade_type);
			},
			// app 支付宝支付
			aliPay() {
				commonPay.aliPay(this.trade_type);
			},
			// H5(微信端)支付
			wechatH5pay() {
				commonPay.h5WechatPay(this.trade_type);
			},
			// 微信小程序支付
			weixinAppletPay() {
				commonPay.miniAppWechatPay(this.trade_type);
			},
			/**  
			 * 根据参数名 获取 URL 路径中的参数  
			 * @param {String} name 要读取的参数名称  
			 */
			getUrlParam(name) {
				var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
				let url = window.location.href.split('#')[0]
				let search = url.split('?')[1]
				if (search) {
					var r = search.substr(0).match(reg)
					if (r !== null) return unescape(r[2])
					return null
				} else {
					return null
				}
			},
			async wxAuthorize() {
				let link = window.location.href;
				let _this = this;
				let wx_code = this.getUrlParam('code'); // 地址解析 
				// 已经授权登录过的就不用再授权了  
				// if (store.state.token) return;  
				// 如果拿到code，调用授权接口，没有拿到就跳转微信授权链接获取    
				if (wx_code) {
					// 调用后台接口，授权
					var params = {
						"secret": wx_code,
						"app_type": "wechat"
					}
					let res = await Api.apiCall('post', Api.index.wxAuth, params);
					if (res) {
						var userInfo = uni.getStorageSync('userInfo');
						userInfo.we_chat_openid = res.we_chat_openid; //微信公众号用户openID
						this.login(userInfo); //把微信公众号用户OpenID刷新用户信息缓存中
						this.loadData();

					}
				} else {
					// 微信公众号appID
					let appid = Api.wx_chat_appid;
					//1.使用encodeURIComponent以及JSON.stringify()方法对对象进行字符串化和编码，这样可以控制url参数的长度，参考示例代码（uni-app书写方式，微信小程序自己改。）  
					let uri = encodeURIComponent(link);
					//2.接受信息的页面使用JSON.parse()以及decodeURIComponent()接收和解码参数。
					//snsapi_base   //snsapi_base    scope = snsapi_base（不弹出授权页面，直接跳转，只能获取用户 openid ）。  
					//snsapi_userinfo  弹出  
					let authURL =
						`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${uri}&response_type=code&scope=snsapi_base&state=123#wechat_redirect`;
					window.location.href = authURL;
				}
			},
			minApp_Authorize(){
				var _this = this;
				uni.login({
					provider: 'weixin',
					success: (loginRes) => {
						uni.setStorage({ //缓存用户openid
							key: 'wx_mini_code',
							data: loginRes.code
						})
						_this.wxMiniAuth(loginRes.code);//通过服务器获取微信小程序openID
						// 获取用户信息
				// 		uni.getUserInfo({
				// 			provider: 'weixin',
				// 			success: function(infoRes) {
				// 				console.log('用户昵称为：' + infoRes.userInfo.nickName);
				// 				console.log(JSON.stringify(infoRes.userInfo));
				// 				uni.showModal({
				// 					title: '暂未开通',
				// 					content: infoRes
				// 				})
				// 				uni.setStorage({ //缓存用户登陆状态
				// 					key: 'userInfo',
				// 					data: infoRes.userInfo
				// 				})
				
				// 			}
				// 		});
						//获取用户openid 
				// 		uni.request({
				// 			url: 'https://api.weixin.qq.com/sns/jscode2session?appid=wx1089bf8162b25764&secret=395b76eb55d21bca548b5b2b08cd1e3a&js_code=' +
				// 				loginRes.code + '&grant_type=authorization_code',
				// 			data: {
				// 				text: 'uni.request'
				// 			},
				// 			header: {
				
				// 				'custom-header': 'hello' //自定义请求头信息
				// 			},
				// 			success: (res) => {
				// 				console.log('********res*******', JSON.stringify(res));
				// 				uni.showToast({
				// 					title: JSON.stringify(res),
				// 					icon: 'none'
				// 				})
				// 				uni.showModal({
				// 					title: '微信小程序',
				// 					content: JSON.stringify(res.data)
				// 				})
				// 				uni.setStorage({ //缓存用户openid 
				// 					key: 'userInfoOpenId',
				// 					data: res.data.openid
				// 				})
				
				// 			}
				// 		});
				
					},
					fail: (e) => {
						plus.nativeUI.alert("fail: " + JSON.stringify(e));
						console.log("fail: " + JSON.stringify(e));
					}
				});
			},
			async wxMiniAuth(code){
				var params = {
					"secret": code,
					"app_type": "mini"
				}
				let res = await Api.apiCall('post', Api.index.wxMiniAuth, params);
				if (res) {
					var userInfo = uni.getStorageSync('userInfo');
					userInfo.mini_openid = res.mini_openid; //微信小程序openID
					this.login(userInfo); //微信小程序OpenID刷新用户信息缓存中
					this.loadData();
				}
			}
		}
	}
</script>

<style lang='scss'>
	.app {
		width: 100%;
		height: 100vh;
		position: relative;
		background-color: #FFF;
	}

	/* .price-box {
		background-color: #fff;
		height: 265upx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		font-size: 28upx;
		color: #909399;

		.price {
			font-size: 50upx;
			color: #303133;
			margin-top: 12upx;

			&:before {
				content: '￥';
				font-size: 40upx;
			}
		}
	} */
	
	.price-box {
		background-color: #fff;
		padding: 20upx 0 40upx 0;
		box-sizing: border-box;
		// height: 265upx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		font-size: 28upx;
		color: #909399;
	
		.price {
			font-size: 70upx;
			// color: #303133;
			color: #FFBC21;
			margin-top: 12upx;
	
			&:before {
				content: '￥';
				font-size: 40upx;
			}
		}
	}

	.pay-type-list {
		margin-top: 50upx;
		background-color: #fff;
		padding-left: 60upx;

		.type-item {
			height: 120upx;
			padding: 20upx 0;
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding-right: 60upx;
			font-size: 30upx;
			position: relative;
		}

		.icon {
			width: 100upx;
			font-size: 52upx;
		}

		.icon-erjiye-yucunkuan {
			color: #fe8e2e;
		}

		.icon-weixinzhifu {
			color: #36cb59;
		}

		.icon-alipay {
			color: #01aaef;
		}

		.tit {
			font-size: $font-lg;
			color: $font-color-dark;
			margin-bottom: 4upx;
		}

		.con {
			flex: 1;
			display: flex;
			flex-direction: column;
			font-size: $font-sm;
			color: $font-color-light;
		}
	}

/* 	.mix-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 630upx;
		height: 80upx;
		margin: 80upx auto 30upx;
		font-size: $font-lg;
		color: #fff;
		background-color: #FFBC21;
		border-radius: 10upx;
		box-shadow: 1px 2px 5px rgba(219, 63, 96, 0.4);
	} */
	.footer{
		width: 100vw;
		height: 100upx;
		display: flex;
		justify-content: center;
		align-items: center;
		box-sizing: border-box;
		padding: 0 40upx;
		position: fixed;
		bottom: 0;
		border-top: 1upx solid $uni-border-color;
		background-color: #FFF;
		.pay-botton{
			width: 100%;
			height: 80upx;
			outline: none;
			background-image: linear-gradient(to right, #FFBC21, #ffd743);
			border-radius: 40upx;
			color: #FFF;
		}
	}
</style>
